<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @cancel="handleCancel"
    :footer="null">

    <a-row :gutter="10">
      <a-col :span="6">
        <a-card title="用户基本信息" :bodyStyle="bodyStyle">
          <a-form :form="form">
            <a-col :span="colSpan">
              <a-form-item label="账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入账号" v-decorator.trim="[ 'username', validatorRules.username]" :readOnly="!!model.userId" :disabled="disableSubmit"/>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入姓名" v-decorator.trim="[ 'realname', validatorRules.realname]" :disabled="disableSubmit"/>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入手机号码" v-decorator="[ 'phone', validatorRules.phone]" :disabled="disableSubmit" />
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-dict-select-tag placeholder="请选择性别" :triggerChange="true" v-decorator="['sex']" dictCode="sex" :disabled="disableSubmit"></j-dict-select-tag>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="座机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入座机号" v-decorator="[ 'telephone', validatorRules.telephone]" :disabled="disableSubmit" />
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入邮箱" v-decorator="[ 'email', validatorRules.email]" :disabled="disableSubmit" />
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-date-picker
                  style="width: 100%"
                  placeholder="请选择生日"
                  v-decorator="['birthday']"
                  :getCalendarContainer="node => node.parentNode"/>
              </a-form-item>
            </a-col>
            <div class="drawer-bootom-button" v-show="!disableSubmit">
              <a-button @click="handleSubmit" type="primary">提交</a-button>
            </div>
          </a-form>
        </a-card>
      </a-col>
      <a-col :span="18">
        <a-card title="关联组织">
          <div style="margin-top: -15px;margin-left:8px;margin-bottom: 9px;">
            <a-row :gutter="24">
              <a-button
                v-show="!disableSubmit"
                v-has="'user:add'"
                type="primary"
                @click="handleAdd"
                icon="plus"
                style="margin-left: 8px">新增</a-button>
            </a-row>
          </div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            @change="handleTableChange">

            <span slot="action" slot-scope="text, record">
              <a v-show="!disableSubmit" @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical"/>
              <a-popconfirm v-show="!disableSubmit" title="确定删除吗?" @confirm="() => doDelete(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>

          </a-table>
          <user-tenant-edit-modal ref="editModalForm" @ok="modalFormOk"></user-tenant-edit-modal>
        </a-card>
      </a-col>
    </a-row>
  </j-modal>
</template>

<script>

  import { api, addTenantUser, editTenantUser } from '../service'
  import { duplicateCheck } from '@api/api'
  import JDictSelectTag from '@comp/dict/JDictSelectTag'
  import UserTenantEditModal from './UserTenantEditModal.vue'
  import pick from 'lodash.pick';
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { deleteAction, getAction } from '@api/manage';

  export default {
    name: 'UserTenantModal',
    mixins: [JeecgListMixin],
    components: {
      JDictSelectTag,
      UserTenantEditModal
    },
    data () {
      let that = this;
      return {
        disableMixinCreated: true,
        drawerWidth: 700,
        width: 1400,
        visible: false,
        title: '操作',
        tenantId: '',
        userId: '',
        columns: [
          {
            title: '#',
            align: 'center',
            width: 60,
            dataIndex: 'rowIndex',
            customRender: function (t, r, index) {
              return (that.ipagination.current - 1) * that.ipagination.pageSize + index + 1;
            }
          },
          {
            title: '组织名称',
            ellipsis: true,
            dataIndex: 'tenantName'
          }, {
            title: '角色',
            dataIndex: 'roleNames',
            ellipsis: true,
            customRender: function(text) {
              return text ? text.replaceAll(',', '，') : '';
            }
          }, {
            title: '部门',
            dataIndex: 'departNames',
            ellipsis: true,
            customRender: function(text) {
              return text ? text.replaceAll(',', '，') : '';
            }
          }, {
            title: '负责部门',
            dataIndex: 'departIdsName',
            ellipsis: true,
            customRender: function(text) {
              return text ? text.replaceAll(',', '，') : '';
            }
          }, {
            title: '工号',
            dataIndex: 'workNo'
          }, {
            title: '职务',
            dataIndex: 'postName',
            ellipsis: true
          }, {
            title: '是否超管',
            align: 'center',
            dataIndex: 'userIdentity',
            customRender: function(text) {
              if (text === 1) {
                return '是';
              } else {
                return '否';
              }
            }
          }, {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            fixed: 'right',
            width: 120,
            align: 'center'
          }
        ],
        disableSubmit: false,

        form: this.$form.createForm(this),

        model: {},

        colSpan: 24,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        bodyStyle: { 'min-height': '500px' },
        confirmDirty: false,
        validatorRules: {
          username: {
            rules: [{
              required: true, message: '请输入账号!'
            }, {
              validator: this.validateUsername
            }]
          },
          realname: { rules: [{ required: true, message: '请输入姓名!' }, { validator: this.validateRealName }] },
          password: {
            rules: [{
              required: true,
              pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,16}$/,
              message: '密码由8-16位数字、大小写字母和特殊符号组成!'
            }, {
              validator: this.validateToNextPassword
            }]
          },
          confirmpassword: { rules: [{ required: true, message: '请重新输入登录密码!' }, { validator: this.compareToFirstPassword }] },
          phone: { rules: [{ required: true, message: '请输入手机号!' }, { validator: this.validatePhone }] },
          email: { rules: [{ validator: this.validateEmail }] },
          telephone: { rules: [{ pattern: /^\+?[1-9]\d{0,14}$/, message: '请输入正确格式的座机号！' }] }
        },

        url: {
          list: api.listUserTenant(this.tenantId, this.userId),
          delete: ''
        }
      }
    },
    created () {
    },
    computed: {
    },
    watch: {
      tenantId() {
        this.url.list = api.listUserTenant(this.tenantId, this.userId);
      },
      userId() {
        this.url.list = api.listUserTenant(this.tenantId, this.userId);
      }
    },
    methods: {
      edit (record, tenantId) {
        let that = this;
        that.tenantId = tenantId;
        that.userId = record.userId;
        that.model = Object.assign({}, record);
        that.visible = true;
        that.form.resetFields();
        that.resetScreenSize();
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(this.model, 'username', 'realname', 'sex', 'phone', 'telephone', 'email', 'birthday'))
        });

        // 查询关联企业列表
        this.queryParam.tenantId = tenantId;
        this.queryParam.userId = record.userId;
        this.url.list = api.listUserTenant(this.tenantId, this.userId);
        this.loadData(1);
      },
      close () {
        this.visible = false;
      },
      doDelete(record) {
        this.url.delete = api.delete(record.userId, record.tenantId)
        var that = this;
        deleteAction(that.url.delete, {}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);

            let params = that.getQueryParams();// 查询条件
            that.loading = true;
            getAction(that.url.list, params).then((res) => {
              if (res.success) {
                // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                that.dataSource = res.result.rows || res.result;
                if (res.result.totalRows) {
                  that.ipagination.total = res.result.totalRows;
                } else {
                  that.ipagination.total = 0;
                }
                if (this.dataSource.length === 0) {
                  this.$emit('ok');
                  this.handleCancel();
                }
              }
              if (res.code === 510) {
                that.$message.warning(res.message)
              }
              that.loading = false;
            })
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      handleSubmit () {
        let that = this;
        that.form.validateFields((err, values) => {
          if (!err) {
            if (that.model.userId) {
              values.id = that.model.userId;
            }
            let obj;
            if (!values.id) {
              obj = addTenantUser(values);
            } else {
              obj = editTenantUser(values);
            }
            obj.then(res => {
              if (res.success) {
                // this.close();
                that.$message.success(res.message);
                this.$emit('ok');
              } else {
                this.$message.error(res.message);
              }
            });
          }
        })
      },
      handleCancel () {
        this.close();
        this.$emit('ok');
      },
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth;
        } else {
          this.drawerWidth = 700;
        }
      },

      validateUsername(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 21) {
            let params = {
              tableName: 'sys_user',
              fieldName: 'username',
              fieldVal: value,
              dataId: this.model.userId,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('用户名已存在!')
              }
            });
          } else {
            callback('用户名长度不能大于20个字符!')
          }
        }
      },
      validateRealName(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 21) {
            callback()
          } else {
            callback('用户姓名长度不能大于20个字符!')
          }
        }
      },
      validatePhone(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
            let params = {
              tableName: 'sys_user',
              fieldName: 'phone',
              fieldVal: value,
              dataId: this.model.userId,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('手机号已存在!')
              }
            })
          } else {
            callback('请输入正确格式的手机号码!');
          }
        }
      },
      validateToNextPassword  (rule, value, callback) {
        let form = this.form;
        let confirmpassword = form.getFieldValue('confirmpassword');

        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！');
        }
        if (value && this.confirmDirty) {
          form.validateFields(['confirmpassword'], { force: true })
        }
        callback();
      },
      compareToFirstPassword (rule, value, callback) {
        const form = this.form;
        if (value && value !== form.getFieldValue('password')) {
          callback('两次输入的密码不一样！');
        } else {
          this.confirmDirty = false
          form.validateFields(['password'], { force: true })
          callback()
        }
      },
      validateEmail(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 51) {
            if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
              var params = {
                tableName: 'sys_user',
                fieldName: 'email',
                fieldVal: value,
                dataId: this.userId
              };
              duplicateCheck(params).then((res) => {
                console.log(res)
                if (res.success) {
                  callback()
                } else {
                  callback('邮箱已存在!')
                }
              })
            } else {
              callback('请输入正确格式的邮箱!')
            }
          } else {
            callback('邮箱的长度不能大于50个字符!')
          }
        }
      },
      handleConfirmBlur (e) {
        const value = e.target.value;
        this.confirmDirty = this.confirmDirty || !!value
      },

      handleEdit: function (record) {
        this.$refs.editModalForm.edit(record, this.tenantId);
        this.$refs.editModalForm.title = '编辑';
        this.$refs.editModalForm.disableSubmit = false;
      },
      handleAdd: function () {
        this.$refs.editModalForm.add(this.userId, this.tenantId);
        this.$refs.editModalForm.title = '新增';
        this.$refs.editModalForm.disableSubmit = false;
      }
    }
  }
</script>

<style scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: -1px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    border-bottom: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>
